<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Projects List | Pythagora Lab</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="/public/styles/styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/diff2html/3.4.17/diff2html.min.css">
    <style>
        thead th {
            position: sticky;
            top: 0;
            background: white;
            z-index: 100;
        }
        .project-states-container {
            height: calc(100vh - 250px); /* Adjust based on actual header and form heights */
            overflow-y: scroll;
        }
        /* Full width for the details section */
        .details-container {
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <form method="GET" action="/projects">
            <div class="row">
                <div class="col-md-6">
                    <h3>Projects</h3>
                    <select class="custom-select mb-3" name="projectId" id="projectSelect">
                        <option selected>Select a project</option>
                        <% projects.forEach(project => { %>
                            <option value="<%= project.id %>" <%= selectedProjectId === project.id ? 'selected' : '' %>><%= project.name %></option>
                        <% }); %>
                    </select>
                </div>
                <% if (branches && branches.length > 0) { %>
                    <div class="col-md-6">
                        <h3>Branches</h3>
                        <select class="custom-select mb-3" name="branchId" id="branchSelect">
                            <option selected>Select a branch</option>
                            <% branches.forEach(branch => { %>
                                <option value="<%= branch.id %>" <%= selectedBranchId === branch.id ? 'selected' : '' %>><%= branch.name %></option>
                            <% }); %>
                        </select>
                    </div>
                <% } %>
            </div>

            <!-- Collapsible Filter Section -->
            <div id="filterContainer" class="collapse">
                <div class="row mt-3">
                    <div class="col form-group">
                        <input type="text" class="form-control" id="epicSearch" name="epic" placeholder="Epic description" value="<%= epic %>">
                    </div>
                    <div class="col form-group">
                        <input type="text" class="form-control" id="taskSearch" name="task" placeholder="Task description" value="<%= task %>">
                    </div>
                    <div class="col form-group">
                        <input type="text" class="form-control" id="iterationSearch" name="iteration" placeholder="Iteration" value="<%= iteration %>">
                    </div>
                    <div class="col form-group">
                        <input type="text" class="form-control" id="requestSearch" name="llm_request" placeholder="LLM request" value="<%= llm_request %>">
                    </div>
                    <div class="col form-group">
                        <input type="text" class="form-control" id="agentSearch" name="agent" placeholder="Agent" value="<%= agent %>">
                    </div>
                </div>
            </div>

            <!-- Filter Toggle and Submit Button -->
            <div class="row mt-3 mb-3">
                <div class="col">
                    <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#filterContainer">Toggle Filters</button>
                    <button type="submit" class="btn btn-primary">Apply Filters</button>
                </div>
            </div>
        </form>

        <% if (projectStates && projectStates.length > 0) { %>
            <h3>Project States</h3>
            <div class="project-states-container">
                <table id="projectTable" class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Epic</th>
                            <th>Task</th>
                            <th>Iterations</th>
                            <th>Step</th>
                            <th>LLM requests</th>
                            <th>Prompts</th>
                            <th>Agent</th>
                            <th>Files</th>
                            <th>User inputs</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <% projectStates.forEach(state => { %>
                            <%
                                let tasks = JSON.parse(state.tasks);
                                let completed_tasks = tasks.filter(t => t.status === 'done');
                                let current_task = Math.min(completed_tasks.length + 1, tasks.length);
                                let total_tasks = tasks.length;
                            %>
                            <tr data-project-state-id="<%= state.id %>"
                                data-branch-id="<%= selectedBranchId %>"
                                data-current-task="<%= current_task %>"
                                data-total-tasks="<%= total_tasks %>">
                                <td><%= state.step_index %></td>
                                <td><a href="javascript:void(0)" class="detail-link" data-detail-type="epic" data-project-state-id="<%= state.id %>">
                                    <% let epics = JSON.parse(state.epics); %>
                                    <%= epics.length %>
                                </a></td>
                                <td><a href="javascript:void(0)" class="detail-link" data-detail-type="task" data-project-state-id="<%= state.id %>">
                                    <%= current_task %> / <%= total_tasks %>
                                </a></td>
                                <td><a href="javascript:void(0)" onclick="fetchDetails('iteration', <%= state.id %>)" class="detail-link" data-detail-type="iteration" data-project-state-id="<%= state.id %>"><%= JSON.parse(state.iterations).length %></a></td>
                                <td><a href="javascript:void(0)" class="detail-link" data-detail-type="step" data-project-state-id="<%= state.id %>">
                                    <%
                                        let steps = JSON.parse(state.steps);
                                        let completed_steps = steps.filter(t => t.completed);
                                    %>
                                    <%= Math.min(completed_steps.length + 1, steps.length) %> / <%= steps.length %>
                                </a></td>
                                <td><a href="javascript:void(0)" class="detail-link" data-detail-type="llmRequests" data-project-state-id="<%= state.id %>">
                                    <%= state.llm_request_count %>
                                </a></td>
                                <td style="overflow: scroll;">
                                    <%
                                    state.templates.forEach((t) => { %>
                                        <div><%= t %></div>
                                    <% }); %>
                                </td>
                                <td style="overflow: scroll;">
                                    <% if (state.agents) state.agents.forEach((p) => { %>
                                        <div><%= p %></div>
                                    <% }); %>
                                </td>
                                <td>
                                    <a href="javascript:void(0)" class="detail-link" data-detail-type="files" data-project-state-id="<%= state.id %>">
                                        <%= state.files_count %>
                                    </a>
                                    <button class="btn btn-sm btn-primary show-diff-btn">Show diff</button>
                                </td>
                                <td><a href="javascript:void(0)" class="detail-link" data-detail-type="userInputs" data-project-state-id="<%= state.id %>">
                                    <%= state.user_inputs_count %>
                                </a></td>
                                <td style="overflow: scroll;"><%= state.action %></td>
                            </tr>
                        <% }); %>
                    </tbody>
                </table>
                <!-- Diff Section -->
                <div id="diffSection" class="mt-4" style="display: none;">
                    <h4>Changed Files</h4>
                    <div id="changedFilesList" class="list-group">
                        <!-- Changed files will be dynamically added here -->
                    </div>
                    <div class="diff-container" id="fileDiffContent" class="mt-3">
                        <div class="diff-column old-line-numbers"></div>
                        <div class="diff-column old-content"></div>
                        <div class="diff-column new-line-numbers"></div>
                        <div class="diff-column new-content"></div>
                        <!-- File diff content will be displayed here -->
                    </div>
                </div>
            </div>
        <% } %>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/diff2html@3.4.48/bundles/js/diff2html.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/diff2html@3.4.48/bundles/js/diff2html-ui.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/diff2html@3.4.48/bundles/css/diff2html.min.css" rel="stylesheet">
    <script src="/public/js/detailsToggle.js"></script>
    <script src="/public/js/toggleVisibility.js"></script>
    <script src="/public/js/diffVisualization.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof Diff2HtmlUI !== 'undefined') {
                initializeDiffVisualization();
            } else {
                console.error('Diff2HtmlUI is not available');
            }
        });
    </script>
    <script>
        function findComparisonRow(currentRow, currentTaskValue, currentTotalTasks) {
            let row = currentRow.previousElementSibling;
            console.log('findComparisonRow')
            console.log(currentTaskValue)
            console.log(currentTotalTasks)
            while (row) {
                const rowTaskValue = parseInt(row.getAttribute('data-current-task'));
                const rowTotalTasks = parseInt(row.getAttribute('data-total-tasks'));

                if (rowTaskValue === currentTaskValue - 1 || rowTotalTasks !== currentTotalTasks) {
                    console.log('Finished comparison row: ', row)
                    return row;
                }
                row = row.previousElementSibling;
            }

            console.log('Finished comparison row with null.')
            return null;
        }

        function fetchDetails(type, id) {
            console.log(`Fetching details for ${type} with ID ${id}`);
            jQuery.ajax({
                url: `/details/${type}/${id}`,
                type: 'GET',
                success: function(data) {
                    // Assuming the server responds with an HTML snippet to be displayed
                    const detailRow = `<tr><td colspan="11">${data}</td></tr>`;
                    jQuery(`a[data-detail-type="${type}"][data-project-state-id="${id}"]`).closest('tr').after(detailRow);
                },
                error: function(error) {
                    console.error('Error fetching details:', error);
                    alert('Error fetching details. Please try again.');
                }
            });
        }
        document.addEventListener("DOMContentLoaded", function() {
            const projectSelect = document.getElementById('projectSelect');
            const branchSelect = document.getElementById('branchSelect');
            const taskSearch = document.getElementById('taskSearch');
            const epicSearch = document.getElementById('epicSearch');
            const iterationSearch = document.getElementById('iterationSearch');
            const requestSearch = document.getElementById('requestSearch');
            const agentSearch = document.getElementById('agentSearch');

            // Check if the form was already submitted
            if (!sessionStorage.getItem('formSubmitted')) {
                // Automatically submit the form if a project is already selected and no search filters are applied
                if (projectSelect && projectSelect.value !== "Select a project" &&
                    (!taskSearch.value && !epicSearch.value && !iterationSearch.value && !requestSearch.value && !agentSearch.value)) {
                    sessionStorage.setItem('formSubmitted', 'true');
                    projectSelect.form.submit();
                }

                // Automatically submit the form if a branch is already selected and no search filters are applied
                if (branchSelect && branchSelect.value !== "Select a branch" &&
                    (!taskSearch.value && !epicSearch.value && !iterationSearch.value && !requestSearch.value && !agentSearch.value)) {
                    sessionStorage.setItem('formSubmitted', 'true');
                    branchSelect.form.submit();
                }
            } else {
                // Clear the flag after the form is submitted and reloaded
                sessionStorage.removeItem('formSubmitted');
            }
        });
    </script>
</body>
</html>